import {Common} from "./common";
import {TFile} from "obsidian";
import * as path from "path";

export interface LinkSectionInfo {
    hasSection: boolean
    link: string
    section: string
}

export function getFileByLink(link: string, owningNotePath: string, allowInvalidLink: boolean = true): TFile | undefined {
    if (link.trim() === ""){ // JimmyMo process link with only hash e.g. [[#^i0xwp8]]
        return undefined;
    }
    link = splitLinkToPathAndSection(link).link;
    if (allowInvalidLink) {
        return this.app.metadataCache.getFirstLinkpathDest(link, owningNotePath);
    }
    let fullPath = getFullPathForLink(link, owningNotePath);
    return getFileByPath(fullPath);
}

export function splitLinkToPathAndSection(link: string): LinkSectionInfo {
    let res: LinkSectionInfo = {
        hasSection: false,
        link: link,
        section: ""
    }

    if (!link.contains('#'))
        return res;

    //@ts-ignore
    let linkBeforeHash = link.match(/(.*?)#(.*?)$/)[1];
    //@ts-ignore
    let section = link.match(/(.*?)#(.*?)$/)[2];

    // JimmyMo to compatiable to image hash like xxx.png#inline|300
    let isMarkdownSection = section != ""; // && linkBeforeHash.endsWith(".md"); // for links with sections like [](note.md#section)
    let isPdfPageSection = section.startsWith("page=") && linkBeforeHash.endsWith(".pdf"); // for links with sections like [](note.pdf#page=42)

    if (isMarkdownSection || isPdfPageSection) {
        res = {
            hasSection: true,
            link: linkBeforeHash,
            section: section
        }
    }

    return res;
}

function getFullPathForLink(link: string, owningNotePath: string): string {
    link = splitLinkToPathAndSection(link).link;
    link = Common.normalizePathForFile(link);
    owningNotePath = Common.normalizePathForFile(owningNotePath);

    let parentFolder = owningNotePath.substring(0, owningNotePath.lastIndexOf("/"));
    let fullPath = path.join(parentFolder, link);

    fullPath = Common.normalizePathForFile(fullPath);
    return fullPath;
}
function getFileByPath(path: string): TFile {
    path = Common.normalizePathForFile(path);
    return this.app.vault.getAbstractFileByPath(path) as TFile;
}